package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.domain.dto.DeviceDataPageQueryDto;
import com.zzyl.nursing.domain.pojo.Device;
import com.zzyl.nursing.domain.pojo.DeviceData;
import com.zzyl.nursing.job.IotMsgHeader;
import com.zzyl.nursing.job.IotMsgNotifyData;
import com.zzyl.nursing.job.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 * @author alexis
 * @date 2025-05-30
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Override
    public void batchSave(IotMsgNotifyData notifyData) {
        // 1-数据判断
        // 判断设备是否存在
        IotMsgHeader header=notifyData.getHeader();
        String deviceId=header.getDeviceId();
        Device device=deviceService.lambdaQuery()
                                   .eq(Device::getIotId,deviceId)
                                   .one();
        if (ObjectUtil.isNull(device)) {
            return;
        }
        List<IotMsgService> services=notifyData.getBody()
                                               .getServices();
        if (CollectionUtil.isEmpty(services)) {
            return;
        }
        // 2-对properties数据进行循环构建DeviceData然后做批量保存
        services.forEach(service -> {
            LocalDateTime eventTime=LocalDateTimeUtil.parse(service.getEventTime(),"yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime alarmTime=eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                                             .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                                             .toLocalDateTime();
            Map<String, Object> properties=service.getProperties();
            // 创建一个集合收集循环的DeviceData，然后做批量保存，这里设置一定容量主要是考虑集合底层优化；
            List<DeviceData> deviceDataList=new ArrayList<>(properties.size());
            properties.forEach((k,v) -> {
                // 填充设备相关字段
                DeviceData deviceData=BeanUtil.toBean(device,DeviceData.class,CopyOptions.create()
                                                                                         .setIgnoreProperties("id"));
                deviceData.setAccessLocation(device.getBindingLocation());
                
                // 填充设备属性值
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v.toString());
                deviceData.setAlarmTime(alarmTime);
                deviceDataList.add(deviceData);
            });
            // 批量保存
            saveBatch(deviceDataList);
            // 3-@TODO 将设备上报的数据存入到redis
            stringRedisTemplate.opsForHash()
                               .put(CacheConstants.IOT_DEVICE_LAST_DATA,deviceId,JSONUtil.toJsonStr(deviceDataList));
        });
    }
    
    /**
     * 查询设备数据
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }
    
    /**
     * 查询设备数据列表
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageQueryDto deviceDataPageQueryDto) {
        // 1-MP实现条件过滤分页查询：select * from device_data where function_id=? and device_name=? limit ?,?
        String functionId=deviceDataPageQueryDto.getFunctionId();
        String deviceName=deviceDataPageQueryDto.getDeviceName();
        // 要求functionId和deviceName不能为空
        if (StrUtil.isBlank(functionId) || StrUtil.isBlank(deviceName)) {
            throw new ServiceException("请求的functionId和deviceName不能为空");
        }
        LocalDateTime startTime=deviceDataPageQueryDto.getStartTime();
        LocalDateTime endTime=deviceDataPageQueryDto.getEndTime();
        if (ObjectUtil.isNull(startTime) || ObjectUtil.isNull(endTime)) {
            throw new ServiceException("请求的时间范围不能为空");
        }
        Page<DeviceData> page=this.lambdaQuery()
                                  .eq(DeviceData::getFunctionId,functionId)
                                  .eq(DeviceData::getDeviceName,deviceName)
                                  .between(DeviceData::getAlarmTime,startTime,endTime)
                                  .page(Page.of(deviceDataPageQueryDto.getPageNum(),deviceDataPageQueryDto.getPageSize()));
        // 2-构建返回对象TableDataInfo
        return TableDataInfo.getDataTable(page.getRecords(),page.getTotal());
    }
    
    /**
     * 新增设备数据
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }
    
    /**
     * 修改设备数据
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }
    
    /**
     * 批量删除设备数据
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }
    
    /**
     * 删除设备数据信息
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }
}
